#pragma once
#include <string>
namespace yunshan
{
class LeeString;
template<class T> 
class StringSegment
{
	private:
		StringSegment();
		StringSegment(const T *t);
		StringSegment(const T *t, int len);
		~StringSegment();
	private:
		T * m_str;
		int m_refCount;
		int m_strLen;
		int m_capability;
	private:		
		int AddRef();
		void Release();
		bool operator == (StringSegment<T> &other)
		{
			return (this==&other) || strcmp(m_str, other.m_str)==0;
		}
		friend StringSegment& operator + (const StringSegment<T> &s1,const StringSegment<T> &s2)
		{
		StringSegment * temp =new StringSegment();
		temp->m_strLen = s1.m_strLen + s2.m_strLen;
		temp->m_capability=temp->m_strLen + 1;
		temp->m_str = new T[temp->m_capability];
		memcpy(temp->m_str, s1.m_str,s1.m_strLen);
		memcpy(temp->m_str+s1.m_strLen, s2.m_str,s2.m_strLen+1);
		return *temp;
		}	

		friend class LeeString;
};
template<class T>
int Len(T *t)
{
	if(t==NULL) return 0;
	int len=0;
	while(t[len++]);
	return len-1;
}
template<class T> StringSegment<T>::StringSegment()
{
	this->m_strLen = 0;
	this->m_capability = 0;
	this->m_str = NULL;
	this->m_refCount = 1;
}

template<class T> StringSegment<T>::StringSegment(const T*  str)
{
	if(str==NULL || strcmp(str,"")==0)
	{
	this->m_strLen = 0;
	this->m_capability = 0;
	this->m_str = NULL;
	this->m_refCount = 0;
	}
	else
	{
	this->m_strLen = Len(str);
	this->m_capability = this->m_strLen + 1;
	this->m_str = new T[this->m_capability];
	memcpy(this->m_str, str,this->m_capability);
	this->m_refCount = 1;
	}
}


template<class T> StringSegment<T>::StringSegment(const T*  str, int len)
{
	if(str==NULL || strcmp(str,"")==0 || len <= 0)
	{
	this->m_strLen = 0;
	this->m_capability = 0;
	this->m_str = NULL;
	this->m_refCount = 0;
	}
	else
	{
	this->m_strLen = len;
	this->m_capability = this->m_strLen + 1;
	this->m_str = new T[this->m_capability];
	memcpy(this->m_str, str,this->m_strLen);
	this->m_str[m_strLen] = NULL;
	this->m_refCount = 1;
	}
}

template<class T>
StringSegment<T>::~StringSegment()
{
	if(this->m_str != NULL)
	{
		delete [] this->m_str;
	}
}

template<class T>
int StringSegment<T>::AddRef()
{
	this->m_refCount++;
	return this->m_refCount;
}

template<class T>
void StringSegment<T>::Release()
{
	this->m_refCount--;
	if(this->m_refCount<=0)
	{
		delete this;
	}
}
typedef StringSegment<char> StringBuf;
typedef StringSegment<char> WStringBuf;

}
